package com.wxz.gblw.cjg.controller;

import com.alibaba.fastjson.JSON;
import com.wxz.gblw.cjg.common.Result;
import com.wxz.gblw.cjg.common.base.BaseWxzController;
import com.wxz.gblw.cjg.common.base.BaseWxzVoEntity;
import com.wxz.gblw.cjg.common.model.RequestFilters;
import com.wxz.gblw.cjg.entity.Knowledge;
import com.wxz.gblw.cjg.mapper.KnowledgeMapper;
import com.wxz.gblw.cjg.service.KnowledgeService;
import com.wxz.gblw.cjg.utils.ResourceUtil;
import com.wxz.gblw.cjg.vo.KnowledgeVo;
import org.apache.commons.io.FileUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * Knowledge
 * @author xiangzhong.wang
 * @date 2019-12-31 15:17:33
 */
@RestController
@RequestMapping("/knowledge")
public class KnowledgeController extends BaseWxzController<KnowledgeService, KnowledgeMapper, Knowledge> {

    /**
     * 添加
     * @param model
     * @return 参数配置对象
     */
    @PostMapping
    //public boolean add(@Validated(BaseWxzVoEntity.Add.class) @RequestBody KnowledgeVo model) {
    public Object add(@Validated(BaseWxzVoEntity.Add.class) @RequestBody KnowledgeVo model) {
        Result result = new Result();
        result.setData(this.service.saveEntity(model));
        return result;
    }

    /**
     * 获取详情
     * @param id
     * @return
     */
    @RequestMapping("/{id}")
    public Object get(@PathVariable Long id) {
        Result result = new Result();
        result.setData(this.service.getDetails(id));
        return result;
    }

    /**
     * 编辑
     * @param model
     * @return
     */
    @PutMapping
    public Object edit(@Validated(BaseWxzVoEntity.Update.class) @RequestBody KnowledgeVo model) {
        Result result = new Result();
        result.setData(this.service.editEntity(model));
        return result;
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
//    public boolean delete(@PathVariable Long id) {
    public Object delete(@PathVariable Long id) {
        Result result = new Result();
        result.setData(this.service.deleteEntity(id));
        return result;
    }

    /**
     * 查询
     * @param filters 查询条件
     * @param currentPage 偏移量
     * @param pageSize 长度
     * @return
     */
    @GetMapping
    public Object search(@RequestParam long knowledgeTypeId, @RequestParam long currentPage, @RequestParam long pageSize) throws Exception {
        //@RequestParam String filters,
        String filters="[]";
        List<RequestFilters> params = JSON.parseArray(filters, RequestFilters.class);

        Result result = new Result();
        result.setData(this.service.queryEntitiesByPage(params,knowledgeTypeId,currentPage,pageSize));
        return result;
    }

    @PostMapping("/upload")
    @ResponseBody
    public Object uploadAttachment(HttpServletRequest request, HttpServletResponse response){
        Result result = new Result();
        try {
//            String typeId = request.getParameter("typeId");

            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();

            String path = ResourceUtil.getUploadPath() + "/knowledge";
            List<String> attachments = new ArrayList<>();

            for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {

                MultipartFile mf = entity.getValue();
                //获取该文件的文件名
                String oldFileName = mf.getOriginalFilename();
                String newFileName = UUID.randomUUID().toString().replaceAll("-", "") +
                        oldFileName.substring(oldFileName.lastIndexOf("."));

                File file = new File(path + "/" + newFileName);

                if(!file.exists()){
                    file.mkdirs();
                }

                mf.transferTo(file);
//                TBQrcodeAttachment att = new TBQrcodeAttachment();
//                att.setAttachmentAddress(newFileName);
//                att.setAttachmentName(oldFileName);
//                att.setUploadTime(new Date());
////                att.setUploadUserId(user.getId());
//                commonService.save(att);
                attachments.add(newFileName);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("logo", attachments);
            result.setData(map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     *
     * @Title: downloadAttachment
     * @Description: 下载附件
     * @param @param id
     * @param @param request
     * @param @param response    设定文件
     * @return void    返回类型
     * @author Jrohy
     * @throws
     */
    @RequestMapping("/download")
    @ResponseBody
    public void downloadAttachment(String id ,HttpServletRequest request , HttpServletResponse response){
        OutputStream out = null;
        try {
            String path = ResourceUtil.getUploadPath()+"/knowledge";
            Knowledge knowledge = (Knowledge) this.service.getDetails(Long.valueOf(id));
            File file = new File(path + "/" + knowledge.getLogo());
            System.out.println(file.getPath());
            if (file == null || !file.exists()) {
                return;
            }
            response.reset();
            response.setContentType("application/x-msdownload; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(knowledge.getLogo(), "UTF-8"));
            out = response.getOutputStream();
            out.write(FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
